<?php

namespace PKFrame\Extend;
defined('PATH_PK') or die();

use PKFrame\DataHandler\Arrays;

class Xml
{

    /**
     * @throws \DOMException
     */
    public function Create(string $strRoot, array $data, string $itemName = NULL, string $chiRoot = NULL)
    {
        $dom = new \DOMDocument('1.0', 'utf-8');
        $root = $dom->createElement($strRoot);
        $root->setAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9');
        $root->setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
        $root->setAttribute('xsi:schemaLocation','http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
        $dom->appendChild($root);

        if (empty($chiRoot) == FALSE) {
            $chiXml = $dom->createElement($chiRoot);
            $root->appendChild($chiXml);
        }

        if (Arrays::Is($data)) {
            foreach ($data as $key => $value) {
                if (empty($itemName) == FALSE) {
                    $itemXml = $dom->createElement($itemName);
                    if (isset($chiXml) && empty($chiRoot) == FALSE)
                        $chiXml->appendChild($itemXml);
                    else
                        $root->appendChild($itemXml);
                }

                if (Arrays::Is($value)) {
                    foreach ($value as $k => $v) {
                        $name = $dom->createElement($k);
                        if (isset($itemXml) && empty($itemName) == FALSE)
                            $itemXml->appendChild($name);
                        else
                            $root->appendChild($name);

                        $str = $dom->createTextNode($v);
                        $name->appendChild($str);
                    }
                }
            }
        }
        return $dom->saveXML();
    }

    function Read(string $xml_file, string $strRoot, array $array, string $chiRoot = NULL): array
    {
        $dom = new \DOMDocument('1.0', 'utf-8');
        $result = [];
        $dom->load($xml_file);
        $strData = $dom->getElementsByTagName($strRoot);
        if (empty($chiRoot) == FALSE && method_exists($strData, 'getElementsByTagName'))
            $strData = $strData->getElementsByTagName($strData);

        if (Arrays::Is($array) == FALSE) {
            return $result;
        }
        foreach ($array as $v) {
            if (method_exists($strData, 'getElementsByTagName')) {
                $kData = $strData->getElementsByTagName($v);
                if (method_exists($kData, 'item')) {
                    $result[$v] = $kData->item(0)->nodeValue;
                }
            }
        }
        return $result;
    }
}
